from fastapi import FastAPI, HTTPException
from typing import Any, Dict, List
from database.pg import PostgresDB
app = FastAPI()
from pydantic import BaseModel
from decimal import Decimal



import json
import uvicorn

DATABASE_URL = 'postgresql://postgres:root@localhost:5432/postgres';
postgresDB = PostgresDB(DATABASE_URL)

class SqlReq(BaseModel):
    sql: str

@app.post("/query")
async def execute_query(sqlReq: SqlReq):
    print(sqlReq.sql)
    if not sqlReq.sql:
        raise HTTPException(status_code=400, detail="SQL语句不能为空")
    results = postgresDB.execute_sql(sqlReq.sql, {})
   
    # json 特殊類型導致 json 解析異常 
    # Decimal 存在精度問題
    def json_serial(obj):
        if isinstance(obj, Decimal):
            return float(0)
        if hasattr(obj, 'isoformat'):
            return obj.isoformat()
        raise TypeError(f'Object of type {type(obj)} is not JSON serializable')
    print(results)
    # return '{"key":"111"}'
    return json.loads(json.dumps(results,  default=json_serial))

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

